/**
 * KAYO APPLIANCE CHAINS.
 * Copyright (c) 2016-2016 All Rights Reserved.
 */
package com.leku.video.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 功能描述:响应工具类
 *
 * @author suiying
 * @created 2017年9月30日
 * @version 1.0.0
 */
public class ServletUtil {

	private static final Logger LOG = LoggerFactory.getLogger(ServletUtil.class);

	/**
	 * 
	 * 功能描述: 写入返回值
	 *
	 * @param response
	 * @param data
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	public static void writeResponse(HttpServletResponse response, String data) {

		// 设置字符集
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "text/html;charset=UTF-8");

		try {
			PrintWriter writer = response.getWriter();
			writer.write(data);
		} catch (IOException e) {
			LOG.error("写入Response异常", e);
		}
	}

	/**
	 * 
	 * 功能描述: 读取请求内容
	 *
	 * @param request
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	public static String readRequestMsg(HttpServletRequest request) {

		StringBuffer sb = new StringBuffer();
		try {
			InputStream is = request.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

			String str = null;
			while ((str = br.readLine()) != null) {
				sb.append(str);
			}
		} catch (IOException e) {
			LOG.error("获取请求数据异常", e);
		}
		return sb.toString();
	}

	/**
	 * 
	 * 功能描述:获取请求IP地址(真实)
	 *
	 * @param request
	 * @return
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	public static String getRealIpAddr(HttpServletRequest request) {

		return request.getHeader("X-Real-IP");
	}
}
